撰寫程式,指定程序還原與置於前景視窗
如何撰寫程式來指定程序還原與置於前景視窗,可以透過 Windows API
(1)ShowWindowAsync : The ShowWindowAsync function sets the show state of a window created by a different thread.
(2)SetForegroundWindow : The SetForegroundWindow function puts the thread that created the specified window into the foreground and activates the window. Keyboard input is directed to the window, and various visual cues are changed for the user. The system assigns a slightly higher priority to the thread that created the foreground window than it does to other threads.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Diagnostics;
namespace WindowsFormsApplication12
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
[DllImport("User32.dll")]
private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);
[DllImport("User32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
private const int WS_SHOWNORMAL = 1;
private void button1_Click(object sender, EventArgs e)
{
// 取得目前電腦的處理序
foreach (Process pTarget in Process.GetProcesses())
{
if (pTarget.ProcessName == "KMPlayer") // 取得處理序名稱並與指定程序名稱比較
{
HandleRunningInstance(pTarget);
}
}
}
public static void HandleRunningInstance(Process instance)
{
// 相同時透過ShowWindowAsync還原,以及SetForegroundWindow將程式至於前景
ShowWindowAsync(instance.MainWindowHandle, WS_SHOWNORMAL);
SetForegroundWindow(instance.MainWindowHandle);
}
}
}